package com.dyrj.pig.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.dyrj.base.system.menu.dao.SysMenuMapper;
import com.dyrj.base.system.menu.model.SysMenu;
import com.dyrj.base.system.role.dao.SysRoleMapper;
import com.dyrj.base.system.role.model.SysRole;
import com.dyrj.base.system.user.dao.SysUserMapper;
import com.dyrj.base.system.user.model.SysUser;
import com.dyrj.base.system.utils.SystemUtil;
import com.dyrj.constant.SysFrameConst;
import com.dyrj.pig.bean.TLoginLog;
import com.dyrj.pig.bean.TOrder;
import com.dyrj.pig.bean.TUser;
import com.dyrj.pig.dao.CommonMapper;
import com.dyrj.pig.dao.TLoginLogMapper;
import com.dyrj.pig.dao.TOrderMapper;
import com.dyrj.pig.dao.TUserMapper;
import com.dyrj.pig.result.JsonResult;
import com.dyrj.utils.MD5Util;
import com.dyrj.utils.SmsUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/front")
public class FrontController {

    private static final Log log = LogFactory.get();

    @Autowired
    private CommonMapper commonMapper;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private TOrderMapper tOrderMapper;
    @Autowired
    private TLoginLogMapper loginLogMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private SysRoleMapper roleMapper;
    @GetMapping("/index")
    public String index() {
        return "mobile/index";
    }
    @RequestMapping("/list")
    public JsonResult<List> list(int page, int pageSize, int status, String yhbm, int type,String mobile){

        log.info("page is {}",page);
        log.info("pageSize is {}",pageSize);
        log.info("status is {}",status);
        log.info("yhbm is {}",yhbm);
        log.info("type is {}",type);

        JsonResult<List> result = new JsonResult<>();

        IPage<HashMap> listPage = commonMapper.selectPageInfo(new Page<HashMap>(page,pageSize),status,yhbm,type,mobile);

        List dataList = listPage.getRecords();

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }

    @RequestMapping("/orderList")
    public JsonResult<List> orderList(int page, int pageSize, String yhbm){

        log.info("page is {}",page);
        log.info("pageSize is {}",pageSize);
        log.info("yhbm is {}",yhbm);

        JsonResult<List> result = new JsonResult<>();

        IPage<HashMap> listPage = commonMapper.selectOrderList(new Page<HashMap>(page,pageSize),yhbm);

        List dataList = listPage.getRecords();

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }


    /**
     * 待收款列表
     * @param yhbm
     * @return
     */
    @RequestMapping("/readyCollectMoneyList")
    public JsonResult<List> readyCollectMoneyList(String yhbm){

        log.info("yhbm is {}",yhbm);

        JsonResult<List> result = new JsonResult<>();

        List dataList = commonMapper.getReadyCollectMoneyList(yhbm);

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }

    /**
     * 待付款列表
     * @param yhbm
     * @return
     */
    @RequestMapping("/readyPayMoneyList")
    public JsonResult<List> readyPayMoneyList(String yhbm){

        log.info("yhbm is {}",yhbm);

        JsonResult<List> result = new JsonResult<>();

        List dataList = commonMapper.getReadyPayMoneyList(yhbm);

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }

    @RequestMapping("/subOrderDetail")
    public JsonResult<List> subOrderDetail(String ddbm){

        log.info("ddbm is {}",ddbm);

        JsonResult<List> result = new JsonResult<>();

        List dataList = commonMapper.getSubOrderList(ddbm);

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }

    /**
     * 充值列表
     * @param page
     * @param pageSize
     * @param yhbm 用户编码
     * @return
     */
    @RequestMapping("/paylist")
    public JsonResult<List> paylist(int page, int pageSize,String yhbm){

        log.info("page is {}",page);
        log.info("pageSize is {}",pageSize);
        log.info("yhbm is {}",yhbm);

        JsonResult<List> result = new JsonResult<>();

        IPage<HashMap> listPage = commonMapper.selectPayPageInfo(new Page<HashMap>(page,pageSize),yhbm);

        List dataList = listPage.getRecords();

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }

    /**
     * 提现记录
     * @param page
     * @param pageSize
     * @param yhbm 用户编码
     * @return
     */
    @RequestMapping("/withdrawlist")
    public JsonResult<List> withdrawlist(int page, int pageSize,String yhbm){

        log.info("page is {}",page);
        log.info("pageSize is {}",pageSize);
        log.info("yhbm is {}",yhbm);

        JsonResult<List> result = new JsonResult<>();

        IPage<HashMap> listPage = commonMapper.selectWithdrawPageInfo(new Page<HashMap>(page,pageSize),yhbm);

        List dataList = listPage.getRecords();

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }
    @RequestMapping("/versionlist")
    public JsonResult<List> versionlist(){

        JsonResult<List> result = new JsonResult<>();

        List dataList = commonMapper.getVersionList();

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }

    @RequestMapping("/banklist")
    public JsonResult<List> banklist(String yhbm){

        JsonResult<List> result = new JsonResult<>();

        List dataList = commonMapper.getBankList(yhbm);

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }

    @RequestMapping("/tixianyhklist")
    public JsonResult<List> tiXianYhkList(String yhbm){

        JsonResult<List> result = new JsonResult<>();

        List dataList = commonMapper.getTiXianYhkList(yhbm);

        result.setStatus(0);
        result.setInfo("success");
        result.setData(dataList);

        return result;
    }

    @RequestMapping("/orderDetail")
    public JsonResult<Map> orderDetail(String ddbm){

        log.info("ddbm is {}",ddbm);

        JsonResult<Map> result = new JsonResult<>();

        List dataList = commonMapper.getOrderDetail(ddbm);
        if(dataList != null && dataList.size() > 0){
            result.setData((Map)dataList.get(0));
        }
        result.setStatus(0);
        result.setInfo("success");

        return result;
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @RequestMapping("/sendValidCode")
    public JsonResult<String> sendValidCode(HttpServletRequest request, String phone){

        HttpSession session = request.getSession();

        log.info("phone is {}",phone);

        JsonResult<String> result = new JsonResult<>();

        String code = "";

        //检查手机号的有效性
//        if(!isPhone(phone)){
//            result.setCode(-1);
//            result.setMsg("手机号无效");
//            return result;
//        }

        //检查手机号有效性
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",phone);
        TUser user = tUserMapper.selectOne(queryWrapper);
        if(user != null){
            code = RandomUtil.randomString("123456789",5);
            session.setAttribute("code",code);
            session.setAttribute("time",System.currentTimeMillis());
            log.info("code is {}",code);
            log.info("time is {}",session.getAttribute("time"));
            //todo  sendsms
//            SmsUtil.sendSms(phone,code);
            result.setCode(0);
            result.setMsg("获取验证码成功");
            result.setData(code);
        }else{
            result.setCode(-1);
            result.setMsg("该手机号未授权");
            result.setData("");
        }
        return result;

    }

    /**
     * 充值、提现按钮判断
     * @param yhbm
     * @return
     */
    @RequestMapping("/bindcardcztx")
    public JsonResult<Map> sendBindCardCzTx(HttpServletRequest request, String yhbm){
//        HttpSession session = request.getSession();
        log.info("yhbm is {}",yhbm);
        JsonResult<Map> result = new JsonResult<>();
        String bindcard_tx="0";
        String bindcard_cz="0";
        Map data = new HashMap();
        //根据用户绑定银行卡信息，判断是否可以操作充值、提现按钮。
        List dataList = commonMapper.getBankList(yhbm);
        if(dataList!=null && dataList.size()>0){
            for (Object obj : dataList) {
                Map<String,Object> map_obj = (Map<String,Object>)obj;
                String yhdm = (String)map_obj.get("YHDM");
                if(yhdm!=null && !"".equals(yhdm)){
                    //充值卡
                    bindcard_cz="1";
                }else{
                    bindcard_tx="1";
                }
            }
            log.debug(JSON.toJSONString(dataList));
        }
        result.setCode(0);
        data.put("bindcard_cz",bindcard_cz);
        data.put("bindcard_tx",bindcard_tx);
        result.setData(data);
        return result;

    }
    /**
     * 手机号登录
     * @param phone
     * @return
     */
    @PostMapping("/login")
    public JsonResult<Map> login(HttpServletRequest request, String phone, String code){

        HttpSession session = request.getSession();

        JsonResult<Map> result = new JsonResult<>();

        String type = request.getParameter("type") == null?"":(String) request.getParameter("type");

        String serverCode = (String)session.getAttribute("code");
        Long time = (Long)session.getAttribute("time");

        log.info("code is {}",code);
        log.info("server code is {}",serverCode);
        log.info("time is {}",time);



        log.info("phone is {}",phone);
        //检查手机号的有效性
        //TODO
//        if(!isPhone(phone)){
//            result.setCode(-1);
//            result.setMsg("手机号无效");
//            return result;
//        }

        if(type.equals("android")){

            long seconds = 60;
            System.out.println(System.currentTimeMillis());
            if((System.currentTimeMillis()-time)/1000 > seconds){
                result.setCode(-1);
                result.setMsg("验证码已超时间");
                return result;
            }
            if(serverCode == null || serverCode.trim() == "" || time == null){
                result.setCode(-1);
                result.setMsg("验证码错误");
                return result;
            }
            if(!code.equals(serverCode)){
                result.setCode(-1);
                result.setMsg("验证码验证失败");
                return result;
            }
        }

        //检查手机号有效性
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",phone);
        TUser user = tUserMapper.selectOne(queryWrapper);
        if(user != null){
//            String token = tokenService.getToken(user.getYhbm()+"",user.getMobile());

            String token = "";
            Map data = new HashMap();
            data.put("token",token);
            data.put("yhbm",user.getYhbm());
            data.put("xm",user.getXm());
            data.put("mobile",user.getMobile());
            data.put("lx",user.getLx());
            data.put("idcard",user.getSfzh());
            data.put("sex",user.getSex());
            data.put("address",user.getZz());
            data.put("membercode",user.getMembercode());
            data.put("subno",user.getSubno());
            result.setCode(0);
            result.setMsg("登录成功");
            result.setData(data);

            TLoginLog loginLog = new TLoginLog();
            loginLog.setYhbm(user.getYhbm()+"");
            loginLog.setLogintime(DateUtil.formatDateTime(new Date()));
            loginLog.setYzm(code);
            loginLog.setLoginip(request.getRemoteAddr());
            loginLog.setLlqxx(request.getHeader("user-agent"));
            loginLogMapper.insert(loginLog);
            SysUser sysUser = new SysUser();
//            sysUser.setPhone(user.getMobile());
            sysUser.setAccount("admin");
            String message;
            try {
                sysUser = sysUserMapper.selectByProperty(sysUser);
                sysUser.setVerify("admin");
                Subject subject = SecurityUtils.getSubject();
                // 保存用户信息进session
                subject.getSession().setAttribute(SysFrameConst.SYSTEM_USER, sysUser);
//                log.info("user.getAccount()="+user.getAccount()+", pwd:"+ MD5Util.md5(user.getPassword(), sysUser.getSalt()));
                UsernamePasswordToken upt = new UsernamePasswordToken("admin", MD5Util.md5("123456", sysUser.getSalt()), false);
                subject.login(upt);
                // 获取权限信息
                List<SysRole> roles = roleMapper.selectRoleByUserId(sysUser.getId());
                subject.getSession().setAttribute(SysFrameConst.SYSTEM_ROLES, roles);
                // 获取菜单列表
                // 获取权限字符串
                StringBuffer perms = new StringBuffer();
                roles.forEach(role -> {
                    perms.append(role.getRoleSign());
                    perms.append(",");
                });
                List<SysMenu> menus = sysMenuMapper.selectAllTreeMenu();
                menus = SystemUtil.deleteNotPermisMenu(menus, perms.toString());
                subject.getSession().setAttribute(SysFrameConst.SYSTEM_MENUS, menus);
                // 返回消息
                message = SysFrameConst.ResultCode.SUCCESS.MESSAGE;
//			token = tokenComponent.createJWT(sysUser.getId().toString());
                sysUser.setRolesVo(roles);
                sysUser.setMenusVo(menus);
            } catch (Exception e) {
                sysUser = null;
//                code = SysFrameConst.ResultCode.WRONG_USERNAME_OR_PASSWORD.CODE;
//                log.error("错误的用户名或密码");
//                message = SysFrameConst.ResultCode.WRONG_USERNAME_OR_PASSWORD.MESSAGE;
                e.printStackTrace();
            }

        }else{
            result.setCode(-1);
            result.setMsg("登录失败");
        }
        return result;
    }
    @PostMapping("/addOrder")
    public JsonResult<Map> addOrder(String yhbm){

        log.info("add order {}",yhbm);

        JsonResult<Map> result = new JsonResult<>();

        if(!StrUtil.isEmpty(yhbm)){
            result.setCode(-1);
            result.setMsg("无效用户编码");
        }

        TOrder order = new TOrder();
        order.setDdsj(DateUtil.formatDateTime(new Date()));
        order.setCzcbm(yhbm);
        order.setZt(0);

        int r = tOrderMapper.insert(order);
        if(r > 0){
            result.setCode(0);
            result.setMsg("添加订单成功");
        }else{
            result.setCode(-1);
            result.setMsg("添加订单失败");
        }

        return result;

    }

    @GetMapping("/msg")
    public String getMessage(){
        return "你已通过验证";
    }

    /**
     * 检测手机号有效性
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            return isMatch;
        }
    }

}
